package pkg

import (
	"context"
	"fmt"
	"mini-app/internal/app/grpc/client"
	"mini-app/internal/app/grpc/protoc/system_admin"
	"net/url"
	"regexp"
	"strings"
	"time"

	"192.168.1.75/go-pkg/logx"
	"github.com/PuerkitoBio/goquery"
)

func GenerateRanderOrderID(orderID string) string {
	// 获取当前时间戳(纳秒)的后8位
	timestamp := time.Now().UnixNano()
	timestampStr := fmt.Sprintf("%d", timestamp)
	last8Digits := timestampStr[len(timestampStr)-8:]

	// 组合订单ID和时间戳
	return fmt.Sprintf("%s%s", orderID, last8Digits)
}

// ExtractOrderID 从组合ID中提取原始订单ID
func ExtractOrderID(combinedID string) string {
	// 由于我们知道时间戳部分是8位，所以原始订单ID就是去掉最后8位
	if len(combinedID) <= 8 {
		return combinedID
	}
	return combinedID[:len(combinedID)-8]
}

// 对上传文件的确认
func RichTextConvert(content string) string {
	SystemAdminClient, clientErr := client.GetSystemAdminClient()
	if clientErr != nil {
		return ""
	}
	reader := strings.NewReader(content)
	doc, err := goquery.NewDocumentFromReader(reader)
	if err == nil {
		doc.Find("img").Each(func(i int, s *goquery.Selection) {
			src, _ := s.Attr("src")
			URL, _ := url.Parse(src)
			match, matchErr := regexp.MatchString("^(/file/).*(/temp/).*$", URL.Path)
			if matchErr == nil && match {
				//文件确认
				var req system_admin.ConfirmFileReq
				req.FileUrl = URL.Path
				res, err := SystemAdminClient.ConfirmFile(context.Background(), &req)
				if err != nil && res.Code != 0 {
					logx.Error(context.Background(), "confirm file error", logx.Any("res", res), logx.Any("err", err.Error()))
					return
				}
				ImagePath := URL.Scheme + "://" + URL.Host + res.FileUrl
				s.SetAttr("src", ImagePath) //修改标签的内容
			}
		})
	}
	newContent, _ := goquery.OuterHtml(doc.Selection)
	returnHtml := strings.TrimSuffix(strings.TrimPrefix(newContent, "<html><head></head><body>"), "</body></html>")
	return returnHtml
}
